package com.jijia.webbase.utils;

import cn.hutool.core.lang.TypeReference;
import cn.hutool.json.JSONUtil;
import com.jijia.webbase.config.security.LoginUser;
import com.jijia.webbase.config.security.SaveLoginUser;
import com.jijia.webbase.domain.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import jdk.nashorn.internal.parser.JSONParser;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.util.Base64;
import java.util.Date;
import java.util.concurrent.TimeUnit;

// JwtUtil.java
// 4. JWT工具类
@Component
public class JwtUtil {
    private static final String SECRET_KEY = "6cb64bc47d53cb1a10443d97a3994e712e52c4531be0212b6e603df514e59bcf83aca2aa2a6601e9880e30b624023f266258db5d0ea1487d6732a191157efe98";
    private static final long EXPIRATION = 86400000; // 24小时

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    // 生成JWT
    public String generateToken(UserDetails userDetails) {
        Date now = new Date();
        Date expiryDate = new Date(now.getTime() + EXPIRATION);

        return Jwts.builder()
                .setSubject(userDetails.getUsername())
                .setIssuedAt(now)
                .setExpiration(expiryDate)
                .signWith(SignatureAlgorithm.HS512, SECRET_KEY)
                .compact();
    }

    // 验证并解析JWT
    public Claims parseToken(String token) {
        return Jwts.parser()
                .setSigningKey(SECRET_KEY)
                .parseClaimsJws(token)
                .getBody();
    }


    public static String parseBase64Jwt(String jwtToken) {
        // 移除头部和签名，只解析负载部分
        String[] parts = jwtToken.split("\\.");
        String base64EncodedBody = parts[1]; // 第二部分是负载

        // 解码 Base64 编码的负载
        String payload = new String(Base64.getDecoder().decode(base64EncodedBody));

        return payload;
    }


    // 将token存入Redis
    public void storeUserWithToken(String  key, SaveLoginUser saveLoginUser) {
        redisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(saveLoginUser), EXPIRATION, TimeUnit.MILLISECONDS);
    }

    // 验证Redis中的token是否存在
    public SaveLoginUser getUser(String key) {
        String json = redisTemplate.opsForValue().get(key);
        System.out.println(json);
        SaveLoginUser saveLoginUser = JSONUtil.toBean(redisTemplate.opsForValue().get(key), SaveLoginUser.class);
        if (saveLoginUser == null)
            return null;
        return saveLoginUser;
    }
    //删除redis的key
    public void deleteKey(String key) {
        redisTemplate.delete(key);
    }

}